import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/account_record_entity.dart';
import 'package:flutter_ncsjqz_getx/model/base_entity.dart';
import 'package:flutter_ncsjqz_getx/model/wallet_detail_entity.dart';
import 'package:flutter_ncsjqz_getx/util/pay_auth_share_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';

class MoneyLogic extends GetxController {
  // 0微信支付 1支付宝支付
  int payType = 0;
  // 金额
  TextEditingController textEditingControllerMoney = TextEditingController();
  int totalMoney = 0;
  List<AccountRecordDataList>? xList = [];
  StreamSubscription? streamSubscription;

  setPayType(int value){
    payType = value;
    update();
  }

  /// 获取数据
  getData() async{
    WalletDetailEntity walletDetailEntity = await DioService<WalletDetailEntity>().walletDetail();
    AccountRecordEntity accountRecordEntity = await DioService<AccountRecordEntity>().accountRecordPage({
      "pageSize": 10,
      "currPage": 0,
    });
    if(walletDetailEntity.code == 0) totalMoney = walletDetailEntity.data!.totalAmount!;
    if(accountRecordEntity.code == 0) xList = accountRecordEntity.data!.xList;
    update();
  }

  /// 充值
  recharge() async{
    Map<String,dynamic> data = {
      "payAmount": textEditingControllerMoney.value.text,
      "payType": payType == 0 ? 1 : 2, // 1微信 2支付宝
    };
    BaseEntity walletDetailEntity = await DioService<BaseEntity>().recharge(data);
    if(walletDetailEntity.code==0 && walletDetailEntity.data!=null){
      // 微信支付
      if(walletDetailEntity.data["payType"] == 1){
        PayUtil.wxPay(WxModel.toFormat(walletDetailEntity.data["data"]),);
      }else{
        // 支付宝支付
        PayUtil.alibabaPay(walletDetailEntity.data["data"],onCall: (v){
          if(v==0) {
            toast("支付成功");
            Get.back();
          }
        });
      }
    }
  }

  /// 订阅微信操作
  wxEvent(){
    streamSubscription = weChatResponseEventHandler.listen((event) async {
      // 0	成功	展示成功页面
      // -1	错误	可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
      // -2	用户取消	无需处理。发生场景：用户不支付了，点击取消，返回APP。
      print('微信：${event.errCode}');
      if(event.errCode == 0){
        toast("支付成功");
        Get.back();
      }else if(event.errCode == -2){
        toast("取消了支付，支付失败");
      }else{
        toast("支付失败,微信配置存在错误！请联系管理员");
      }
    });
  }

  /// 退出当前页面 关闭订阅
  closeWxEvent(){
    if(streamSubscription!=null){
      streamSubscription!.cancel();
    }
  }
}
